#!/bin/bash
MODULE=$1
ENV=$2
IS_PRINT_LOG=$3

PORT=1
case "$MODULE" in
  "blade-gateway")
    PORT=8000
    ;;
  "blade-user")
   PORT=8017
    ;;
  "blade-team")
   PORT=8016
    ;;
  "blade-system")
   PORT=8015
    ;;
  "blade-log")
   PORT=8013
    ;;
  "blade-instrument")
   PORT=8012
    ;;
  "blade-customer")
   PORT=8011
    ;;
  "blade-auth")
   PORT=8008
    ;;
  "blade-resource")
   PORT=8009
    ;;
  "blade-develop")
   PORT=10002
    ;;
  *)
    echo "Unknown"
    ;;
esac

# 启动日志
DIR=~/projects/$MODULE/
LOG_PATH=$DIR/log
RESTART_LOG=$LOG_PATH/restart-$MODULE.log
echo '================================' >> $RESTART_LOG
echo `date +%Y%m%d' '%H:%M:%S` >> $RESTART_LOG
echo '================================' >> $RESTART_LOG
echo "PORT: "$PORT  >> $RESTART_LOG
echo "MODULE: "$MODULE  >> $RESTART_LOG

# 检查文件夹是否存在
cd $DIR
echo 'PWD: '$(pwd) >> $RESTART_LOG

if [ ! -d "$LOG_PATH" ]; then
  echo "文件夹不存在，正在创建..."
  mkdir -p "$LOG_PATH"
  echo "文件夹已创建: $LOG_PATH"
else
  echo "文件夹已存在: $LOG_PATH"
fi

if [ "$4" = "1"  ]
then
  cp 20*-$MODULE.jar release/$MODULE.jar
fi

# 检查文件夹是否存在
DIR_PATH="$DIR/history"
if [ ! -d "$DIR_PATH" ]; then
  echo "文件夹不存在，正在创建..."
  mkdir -p "$DIR_PATH"
  echo "文件夹已创建: $DIR_PATH"
else
  echo "文件夹已存在: $DIR_PATH"
fi
# 备份上次的发布到历史文件夹
mv $DIR/*.jar $DIR/history
echo '================after mv 1================' >> $RESTART_LOG
# 重命名发布文件并且移动到 ~/projects 文件夹，等待发布
NEW_NAME=$(date +%Y%m%d%H%M%S)-$MODULE.jar
mv $DIR/release/$MODULE.jar $DIR/release/$NEW_NAME
mv $DIR/release/$NEW_NAME $DIR
echo '================after mv 2================' >> $RESTART_LOG

PID=$(jps | grep $MODULE | cut -f 1 -d ' ')
echo "jps  PID: "$PID >> $RESTART_LOG
if [[ $PID =~ ^[0-9]+$ ]]
then
	echo 'kill -9 '$PID >> $RESTART_LOG
	kill -9 $PID
fi

PID=$(lsof -i :$PORT | head -n 2 | grep java | awk '{printf $2}')
echo "lsof PID: "$PID >> $RESTART_LOG
if [[ $PID =~ ^[0-9]+$ ]]
then
	echo 'kill -9 '$PID >> $RESTART_LOG
	kill -9 $PID
fi

PID=$(netstat -tpln|grep $PORT | cut -d 'N' -f2 | sed -s "s/\/java//g" | sed -s 's/ //g')
echo "netstat PID: "$PID >> $RESTART_LOG
if [[ $PID =~ ^[0-9]+$ ]]
then
	echo 'kill -9 '$PID >> $RESTART_LOG
	kill -9 $PID
fi

#启动
nohup /home/agent/jdk/jdk-17.0.10+7/bin/java -jar $DIR/$NEW_NAME --spring.profiles.active=$ENV -Duser.timezone=Asia/Shanghai --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED >> $LOG_PATH/$MODULE-nohup.log 2>&1 &

PID=$!
echo 'THIS PID: '$PID >> $RESTART_LOG

echo 'release result ==> '$tmp >>  $LOG_PATH/$MODULE-nohup.log

if [ "$3" = "2" -o "$3" = "3" ]
then
        tail -fn 200 $LOG_PATH/$MODULE-nohup.log
fi

# 切换到目标文件夹
HIS_PATH=$DIR/history
echo 'HIS_PATH: '$HIS_PATH >> $RESTART_LOG
cd $HIS_PATH

# 列出目录中的文件，按修改时间排序，并跳过最新的两个文件
files_to_delete=$(ls -t | tail -n +3)

# 循环删除文件
for file in $files_to_delete; do
    rm -f "$file"
    echo "rm old jar: $file" >> $RESTART_LOG
done


